package com.comcast.util;

import java.io.IOException;
import java.util.Iterator;
import java.util.Properties;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.comcast.util.ConfigurationManager;

/**
 * Resolves place holders in the spring configuration file with configurations from
 * {@link ConfigurationManager}.
 *
 * @author Charles Zhao
 */
public class PropertyPlaceholderConfigurer
    extends org.springframework.beans.factory.config.PropertyPlaceholderConfigurer {
    private static Log log = LogFactory.getLog(PropertyPlaceholderConfigurer.class);

    protected ConfigurationManager configurationManager;

    public ConfigurationManager getConfigurationManager() {
		return configurationManager;
	}

	public void setConfigurationManager(ConfigurationManager configurationManager) {
		this.configurationManager = configurationManager;
	}

    /* (non-Javadoc)
	 * @see org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#resolvePlaceholder(java.lang.String, java.util.Properties, int)
	 */
	@Override
	protected String resolvePlaceholder(String placeholder, Properties props,
			int systemPropertiesMode) {
		String value = super.resolvePlaceholder(placeholder, props, systemPropertiesMode);
		if (value == null) {
			value = this.getValue(placeholder);
		}
		return value;
	}

	/* (non-Javadoc)
	 * @see org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#resolvePlaceholder(java.lang.String, java.util.Properties)
	 */
	@Override
	protected String resolvePlaceholder(String placeholder, Properties props) {
		String value = super.resolvePlaceholder(placeholder, props);
		if (value == null) {
			value = this.getValue(placeholder);
		}
		return value;
	}

	protected Properties mergeProperties() throws IOException {
        Properties result = new Properties();
        for (Iterator iter = configurationManager.getKeys(); iter.hasNext();) {
            String key = (String) iter.next();
            result.setProperty(key, this.getValue(key));
        }
        return result;
    }

	private String getValue(String key) {
		String[] values = configurationManager.getStringArray(key);
        if ( values == null || values.length <= 1)
        	return configurationManager.getProperty(key);

        return StringUtils.join(values, ",");
    }
	
	  public Properties getProperties() {
		  try {
			  Properties results =  mergeProperties();
		      return results;
		  }
		  catch(IOException ex) {
		  }
		  return(null);
	  }	
}
